package org.jix.gbook.auth.service.impl;

import cn.hutool.core.util.RandomUtil;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.jix.framework.common.exception.BizException;
import org.jix.framework.common.response.Response;
import org.jix.gbook.auth.config.ThreadPoolConfig;
import org.jix.gbook.auth.constant.RedisKeyConstants;
import org.jix.gbook.auth.enums.ResponseCodeEnum;
import org.jix.gbook.auth.model.vo.verificationCode.SendVerificationCodeReqVO;
import org.jix.gbook.auth.service.VerificationCodeService;
import org.jix.gbook.auth.sms.AliyunSmsHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * @author stark
 * @date 2025/5/12 13:53
 * @description
 **/
@Service
@Slf4j
public class VerificationCodeServiceImpl implements VerificationCodeService {

    @Resource
    private RedisTemplate<String, Object> redisTemplate;
    @Resource(name = "taskExecutor")
    private ThreadPoolTaskExecutor threadPoolTaskExecutor;
    @Resource
    private AliyunSmsHelper aliyunSmsHelper;


    /**
     * 发送短信验证码
     * @param sendVerificationCodeReqVO
     * @return
     */
    @Override
    public Response<?> send(SendVerificationCodeReqVO sendVerificationCodeReqVO) {

        //手机号
        String phone = sendVerificationCodeReqVO.getPhone();
        //构建redisKey
        String key = RedisKeyConstants.buildVerificationCodeKey(phone);

        //判断验证码是否已发送
        Boolean isSent = redisTemplate.hasKey(key);
        if (isSent){
            //若之前发送的的验证码没过期，提示发送频繁
            throw new BizException(ResponseCodeEnum.VERIFICATION_CODE_SEND_FREQUENTLY);
        }

        String verificationCode = RandomUtil.randomNumbers(6);
        log.info("==> 手机号: {}, 已生成验证码：【{}】", phone, verificationCode);
        //调用阿里云短信发送服务
        threadPoolTaskExecutor.submit(() -> {
            String signName = "阿里云短信测试" ;
            String templateCode = "SMS_154950909";
            String templateParam = String.format("{\"code\":\"%s\"}", verificationCode);
            aliyunSmsHelper.sendMessage(signName,templateCode,phone,templateParam);
        });



        //验证码存储到redis，设置过期时间为两分钟
        redisTemplate.opsForValue().set(key,verificationCode,3, TimeUnit.MINUTES);

        return Response.success();
    }
}
